;
(function($, ECar) {
	"use strict";

	var storage = (function() {
		var dataDom = null,
			hostName = location.hostName ? location.hostName : "static",
			isSessionStorage = window.sessionStorage ? true : false;

		function initDataDom() {
			if (dataDom) return dataDom;

			try {
				dataDom = document.createElement('input');
				dataDom.type = 'hidden';
				dataDom.style.display = "none";
				dataDom.addBehavior('#default#userData');
				body.appendChild(this.dataDom);
				var exDate = new Date();
				exDate = exDate.getDate() + 30;
				dataDom.expires = exDate.toUTCString(); //设定过期时间
			} catch (e) {
				dataDom = null;
			}

			return dataDom;
		}

		function setItem(key, value) {
			if (isSessionStorage) {
				window.sessionStorage.setItem(key, JSON.stringify((value)));
			} else if (initDataDom()) {
				dataDom.load(hostName);
				dataDom.setAttribute(key, value);
				dataDom.save(hostName);
			}
		}

		function getItem(key) {
			if (isSessionStorage) {
				return JSON.parse(window.sessionStorage.getItem(key));
			} else if (initDataDom()) {
				dataDom.load(hostName);
				return dataDom.getAttribute(key);
			}
		}

		return {
			setItem: function() {
				setItem(arguments[0], arguments[1]);
			},
			getItem: function() {
				return getItem(arguments[0]);
			}
		}
	})();

	$(document).on("click", function(e) {
		var jTarget = $(e.target);

		if (jTarget.hasClass("select_container") || jTarget.parents(".select_container").length === 1) return;
		$(".select_container").removeClass("active");
	});
	// 
	$(".select_list").mouseleave(function(e) {
		$(this).parent().removeClass("active");
	});

	$(".select_result").mouseleave(function(e) {
		var toElement = $(e.toElement);
		console.dir(toElement);
		console.log($($(this).toElement).parents(".select_list").length);
		if (toElement.hasClass(".select_list") || toElement.parents(".select_list").length > 0) {
			return;
		}
		$(this).parent().removeClass("active");
	});

	$(".select_result").mouseover(function(e) {
		$(this).parent().addClass("active");
		var jSelector = $(".select_item").find("ul[data-item-type='province']");
		if (jSelector.children().length) return;

		var jProvinceNav = $(".select_nav li[data-type='province']"),
			jCityNav = $(".select_nav li[data-type='city']"),
			jRegionNav = $(".select_nav li[data-type='region']"),
			jRegion = $(".select_region"),
			sProvinceName = jProvinceNav.attr("title") ? jProvinceNav.attr("title") : jProvinceNav.text(),
			sCityName = jCityNav.attr("title") ? jCityNav.attr("title") : jCityNav.text(),
			sRegionName = jRegionNav.attr("title") ? jRegionNav.attr("title") : jRegionNav.text();

		//获取省数据
		createItem("province", getRegionData("province", "province"), sProvinceName);

		//获取市级数据
		createItem("city", getRegionData("city", jRegion.data("province-code")), sCityName);

		//获取区级数据
		createItem("region", getRegionData("city", jRegion.data("city-code")), sRegionName);

		//显示区级导航
		toggleState(jRegionNav, "current");
		$(".select_item").find("ul[data-item-type='region']").show().siblings().hide();

		return false;
	});

	$(".select_nav li").on("click", function(e) {
		var sType = $(this).data("type");
		// 切换"选中"状态

		toggleDisplay(regionMap(sType));

		return false;
	});

	$(".select_item").on("click", function(e) {
		var oSelf = e.target,
			sNodeName = oSelf.nodeName.toLowerCase(),
			sText = $(oSelf).attr("title"),
			jParent = $(oSelf).parent(),
			sType = jParent.parent("ul").data("item-type");

		if (sNodeName !== "a") return;

		//更新导航显示区域
		updateNavTxt(sType, sText);

		// 切换标签显示状态
		if (jParent.hasClass("current")) return;
		toggleState(jParent, "current");

		// 切换导航显示状态
		var nType = regionMap(sType),
			oData = null,
			sCode = $(oSelf).data("code"),
			jNav = $(".select_nav"),
			jProvince = $(".select_item ul[data-item-type='province']"),
			jCity = $(".select_item ul[data-item-type='city']"),
			jRegion = $(".select_item ul[data-item-type='region']"),
			jResult = $(".select_region");

		if (nType === 1) { //省
			updateNavTxt("city", "请选择");
			updateNavTxt("region", "请选择");
			jProvince.data("code", sCode); //添加选中"省"对应code
			jNav.find("li[data-type='region']").hide(); //隐藏"区"的导航
			oData = getRegionData("city", sCode); //获取选中"省"对应的市级数据
			createItem("city", oData, ""); //根据市级数据生成列表
		} else if (nType === 2) { //市
			updateNavTxt("region", "请选择");
			jCity.data("code", sCode); //添加选中"市"对应code
			jNav.find("li[data-type='region']").show(); //显示"区"的导航
			oData = getRegionData("city", sCode); //获取选中"市"对应的市级数据
			createItem("region", oData, ""); //根据区数据生成列表
		} else { //区
			jRegion.data("code", sCode); //添加选中"区"对应code

			sText = "";
			$(".select_nav li").each(function() {
				sText += $(this).attr("title"); //获取所选省市区对应的名称
			});

			//添加所选省市区对应的code
			//更新所选省市区对应的名称
			$(".select_region").data("province-code", jProvince.data("code"))
				.data("city-code", jCity.data("code"))
				.data("region-code", sCode)
				.text(sText);

			$(".select_container").removeClass("active");
		}


		nType = nType > 2 ? 0 : (nType + 1);
		toggleDisplay(nType);

		e.stopPropagation();
		e.preventDefault();
		return false;
	});

	function regionMap(type) {
		var oMapping = {
			"province": 1,
			"city": 2,
			"region": 3
		};

		return oMapping[type] ? oMapping[type] : 0;
	}

	function toggleDisplay(type) {
		var sNav = "",
			sItem = "";
		switch (type) {
			case 1:
				sNav = "data-type='province'";
				sItem = "data-item-type='province'";
				break;
			case 2:
				sNav = "data-type='city'";
				sItem = "data-item-type='city'";
				break;
			case 3:
				sNav = "data-type='region'";
				sItem = "data-item-type='region'";
				break;
		}

		if (sNav && sItem) {
			//显示对应的导航
			var jNav = $(".select_nav");
			toggleState(jNav.find("li[" + sNav + "]"), "current");
			//显示对应的区域
			$(".select_item").find("ul[" + sItem + "]").show().siblings().hide();
		}
	}

	function createItem(type, data, name) {
		var jSelector = $(".select_item").find("ul[data-item-type='" + type + "']");

		if (jSelector.length) {
			jSelector.html("");
			var jLi = null,
				sRegionName = "",
				jA = null;
			for (var i = 0; i < data.length; i++) {
				sRegionName = data[i].regionName;

				jLi = $("<li>");
				jA = $("<a>").attr({
					"title": sRegionName,
					"href": "javascript:;"
				}).text(sRegionName.slice(0, 5)).data("code", data[i].regionCode);

				if (sRegionName === name) {
					jLi.addClass("current");
				}

				jLi.append(jA);
				jSelector.append(jLi);
			}
		}
	}

	function getRegionData(type, code) {
		var oResult = storage.getItem(code),
			oUrl = {
				"province": "/base/getProviceAddr.htm",
				"city": "/base/getDistrictAddr.htm"
			},
			sUrl = oUrl[type] ? oUrl[type] : "";
		if (oResult) return oResult;

		$.ajax({
			url: sUrl,
			type: "post",
			async: false,
			data: {
				"parentCode": code
			},
			dataType: "json",
			success: function(data) {
				if (data.result) {
					oResult = JSON.parse(data.result);
					storage.setItem(code, oResult);
				}
			},
			fail: function(e) {}
		});

		return oResult;
	}

	// 更新导航显示区域
	function updateNavTxt(type, text) {
		var jSelector = $(".select_nav").find("li[data-type='" + type + "']");

		if (jSelector.length === 1) {
			jSelector.eq(0).attr("title", text).text(text.slice(0, 5));
		}
	}

	// 切换元素状态
	function toggleState(o, className) {
		if (o instanceof $ && className.length) {
			o.addClass(className).siblings().removeClass(className);
		}
	}
})(jQuery, ECar);